//
//  PersonalDutyViewController.m
//  Nurse
//
//  Created by 张攀 on 13-12-23.
//  Copyright (c) 2013年 RainSets. All rights reserved.
//

#import "PersonalDutyViewController.h"

#import "DutyViewCell.h"
#import "DutyScreeningView.h"
#import "DutyViewListCell.h"
#import "DutyViewButtonCell.h"
#import "DutyScanningViewCell.h"

#import "PatientService.h"
#import "OrdersService.h"
#import "ScanService.h"

#import "BlocksKit.h"
#import "BlocksKit+UIKit.h"
@interface PersonalDutyViewController ()
@property(nonatomic,strong)NSArray* tasks;

-(NSArray*)processTasksData:(NSArray*)rawData;
-(void)onReceiveScanData:(NSNotification*)notification;
-(void)setupData;

@end

@implementation PersonalDutyViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
        [nc addObserver:self selector:@selector(onReceiveScanData:) name:@"PersonalDutyView" object:nil];
         [self setupData];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title  = @"病人任务";
    [self setleftBarButtonItem:@""orImaged:@"head-icon_04.png" Event:@selector(leftBar_clicked:)];
    // Do any additional setup after loading the view from its nib.
    NSDictionary* patient = [[PatientService sharedInstance]currentPatient];
    
    self.pInfoView.txtPatientName.text = [patient valueForKey:@"姓名"];
    self.pInfoView.txtPatientID.text = [NSString stringWithFormat:@"住院号:%@",[patient valueForKey:@"住院号"]];
    self.pInfoView.txtBedNo.text = [NSString stringWithFormat:@"床位号:%@",[patient valueForKey:@"床位号"]];
    NSString*xb= [patient valueForKey:@"性别"];
    if ([xb isEqualToString:@"女"]) {
        self.pInfoView.imgxb.image=[UIImage imageNamed:@"gender-female2.png"];
        
    }
    else{
        self.pInfoView.imgxb.image=[UIImage imageNamed:@"gender-male2.png"];
    }
    
    _dataList = [[NSMutableArray alloc] init];
    ;
   
    
   /* for (int i=0; i<10; i++) {
        
        NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
        [dic setObject:@"检查血压" forKey:@"name"];
        //[dic setObject:@"检查血压" forKey:@"img"];
        NSMutableArray *arr=[[NSMutableArray alloc]init];
        [arr addObject:@"1"];
        [arr addObject:@"1"];
        [arr addObject:@"1"];
        [dic setObject:arr forKey:@"list"];
        arr=nil;
        [_dataList addObject:dic];
        dic=nil;
        
    }*/
    
    self.table_View.sectionFooterHeight = 0;
    self.table_View.sectionHeaderHeight = 0;
}

-(void)setupData{
    NSDictionary* patient = [PatientService sharedInstance].currentPatient;
    NSString* pid = [patient valueForKey:@"住院号"];
    __weak PersonalDutyViewController* this = self;
    [[OrdersService sharedInstance]queryDutiesForPatient:pid withSuccessHandler:^(id result) {
        //NSLog(@"任务.....................");
        //NSLog(@"任务:%@",result);
        if ([result isKindOfClass:[NSArray class]]) {
            this.tasks= result;
            _dataList = [[OrdersService sharedInstance]processTasksData:this.tasks];
            [this.table_View reloadData];
            
        }
    } andFailHandler:^(NSError *error, NSString *title) {
        [[DataEngine sharedInstance]showMessage:[error description] withTitle:@"获取任务信息时失败"];
    }];
    
    
    

}

//相应扫描器
-(void)onReceiveScanData:(NSNotification*)notification{
    //if ([self.title  isEqualToString:@"病人任务"]){
    NSDictionary* userinfo = [notification userInfo];
    NSString* data = [userinfo valueForKey:@"data"];

    
    //[[DataEngine sharedInstance]showMessage:data withTitle:@"扫描器输入"];
    
  //  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%@ CONTAINS[c] %@)", "BR|",data];
    
    
    
    if ([data length] ==9) {
        if (self.isOpen) {
            NSDictionary* tasks = [_dataList objectAtIndex:self.selectIndex.section];
            NSArray* brarray = [data componentsSeparatedByString:@"|"];
            NSString* zyh = [brarray objectAtIndex:1];
            NSString* PaientID = [tasks valueForKey:@"zyh"];
            
            
            //        NSString* zyzbh = [array objectAtIndex:0];
            //        NSString* rwrq = [array objectAtIndex:1];
            if ([zyh isEqualToString:PaientID]){
            [tasks setValue:@"1" forKey:@"scanStatus"];
            [self.table_View reloadData];
            }
            else
            {[[DataEngine sharedInstance]showMessage:
              [NSString stringWithFormat:@"当前扫描病人=%@,医嘱所属住院号=%@",zyh,PaientID]
                                           withTitle:@"扫描病人错误"];
            }
        }else{
            [[DataEngine sharedInstance]showMessage:@"请先扫描需要执行的医嘱项目" withTitle:@"病人任务扫描顺序错误"];
        }
    }
    //长度超过6为医嘱条码
    else if ([data length]>10) {
        NSArray* array = [data componentsSeparatedByString:@"|"];
        
//        NSString* zyzbh = [array objectAtIndex:0];
//        NSString* rwrq = [array objectAtIndex:1];
//        NSString* rwsj = [array objectAtIndex:2];
        
        
        NSString* zyzbh = [array objectAtIndex:1];
        NSString* rwrqsj = [array objectAtIndex:2];
        
        
        NSString* keyValue = [NSString stringWithFormat:@"%@%@",zyzbh,rwrqsj];
        BOOL found = NO;
        for (int i=0;i<[_dataList count];i++) {
            NSDictionary* tasks = [_dataList objectAtIndex:i];
            NSString* taskKey = [tasks valueForKey:@"keyValue"];
            //NSString* scanStatus = [tasks valueForKey:@"scanStatus"];
            if ([taskKey isEqualToString:keyValue]) {
                NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:i];
                NSLog(@"select to indexPath:%@",indexPath);
                [self.table_View selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
                if (!self.isOpen) {
                    
                    [self tableView:self.table_View didSelectRowAtIndexPath:indexPath];
                    
                }else{
                    if (self.selectIndex.section != indexPath.section) {
                        [self tableView:self.table_View didSelectRowAtIndexPath:self.selectIndex];
                        [self tableView:self.table_View didSelectRowAtIndexPath:indexPath];
                       
                    }
                    [tasks setValue:@"0" forKey:@"scanStatus"];
                    
                                  }
                //[tasks setValue:@"1" forKey:@"scanStatus"];
                NSNumber* status = [tasks valueForKey:@"status"];
                if ([status intValue] == 1) {
                    [[DataEngine sharedInstance]
                     showMessage:@"该条医嘱信息已经执行过了!"
                     withTitle:@"提醒核对医嘱信息"];
                    
                }

                found = YES;
                break;
            }
        }
        if (!found) {
            [[DataEngine sharedInstance]
             showMessage:[NSString stringWithFormat:@"主医嘱编号=%@,任务日期时间=%@",zyzbh,rwrqsj]
             withTitle:@"没有找到下列医嘱信息"];
        }

    }
    
   // }
    
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_dataList count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isOpen) {
        if (self.selectIndex.section == section) {
            
            if ([[[_dataList objectAtIndex:section] objectForKey:@"list"] count]>0) {
                return [[[_dataList objectAtIndex:section] objectForKey:@"list"] count]+2;
                
            }
        }
    }
    return 1;
}
- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row==0) {
        return 63;
    }
    return 45;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
   // NSLog(@"indexPath.row=%d,indexPath.section=%d",indexPath.row,indexPath.section);
    
    NSInteger taskIndex = indexPath.section;
    
    NSDictionary* taskRecord = [_dataList objectAtIndex:taskIndex];
    
    NSString* taskType = [taskRecord valueForKey:@"type"];
    
    NSString* scanStatus = [taskRecord valueForKey:@"scanStatus"];
    
   // NSString* taskKey = [taskRecord valueForKey:@"keyValue"];
    
    if (self.isOpen&&self.selectIndex.section == indexPath.section&&indexPath.row!=0) {
        
        NSArray *list = [[_dataList objectAtIndex:self.selectIndex.section] objectForKey:@"list"];
        if(indexPath.row==[list count]+1){
            
            /*************设置为0 规定一定要扫描病人***************/
            if ([scanStatus isEqualToString:@"0"]) {
            /****************************/
                static NSString *CellIdentifier = @"DutyScanningViewCell";
                
                DutyScanningViewCell *cell = (DutyScanningViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                if(cell==nil){
                    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DutyScanningViewCell" owner:self options:nil];
                    cell = [nib objectAtIndex:0];
                }
                cell.img.image=[UIImage imageNamed:@"scan-icon-s.png"];
                cell.describeLab.text=@"请扫描病人信息";
                
                
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                return cell;
                
            }else{
                //下面三个按钮
                static NSString *CellIdentifier = @"DutyViewButtonCell";
                
                DutyViewButtonCell *cell = (DutyViewButtonCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
                if(cell==nil){
                    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DutyViewButtonCell" owner:self options:nil];
                    cell = [nib objectAtIndex:0];
                    [cell.completeBtn setTitle:@"已完成" forState:UIControlStateNormal];
                    [cell.notInBtn setTitle:@"病人不在" forState:UIControlStateNormal];
                    [cell.refusedBtn setTitle:@"病人拒绝" forState:UIControlStateNormal];
                    
                    
                    cell.completeBtn.titleLabel.font=[UIFont systemFontOfSize:14.f];
                    cell.notInBtn.titleLabel.font=[UIFont systemFontOfSize:14.f];
                    cell.refusedBtn.titleLabel.font=[UIFont systemFontOfSize:14.f];
                    
                    [cell.completeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    [cell.notInBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                    [cell.refusedBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                    
                    
                    [cell.completeBtn setBackgroundColor:NavigationBarColor];
                    [cell.notInBtn setBackgroundColor:[UIColor colorWithRed:223/255.0 green:228/255.0 blue:230/255.0 alpha:1.0]];
                    [cell.refusedBtn setBackgroundColor:[UIColor colorWithRed:223/255.0 green:228/255.0 blue:230/255.0 alpha:1.0]];
                    
                    NSMutableArray* idArray = [NSMutableArray array];
                    
                    for (NSDictionary* dict in list) {
                        NSString* taskID = [dict valueForKey:@"任务编号"];
                        [idArray addObject:taskID];
                    }
                    
                    __block NSString* allTaskID = [idArray componentsJoinedByString:@","];
                    __weak PersonalDutyViewController* this = self;
                    
                    [cell.completeBtn bk_addEventHandler:^(id sender) {
                        NSLog(@"completeBtn");
                        //__block NSString* innerAllTaskID = allTaskID;
                        NSLog(@"innerAllTaskID:%@",allTaskID);
                        [[OrdersService sharedInstance]executeDutyForID:allTaskID withStatus:@"1" withSuccessHandler:^(id result) {
                            [[DataEngine sharedInstance]showMessage:@"完成任务成功" withTitle:@"执行任务"];
                            [this tableView:this.table_View didSelectRowAtIndexPath:this.selectIndex];
                            [this setupData];
                        } andFailHandler:^(NSError *error, NSString *title) {
                            [[DataEngine sharedInstance]showMessage:[error description] withTitle:@"执行任务失败"];
                            //[this.table_View reloadData];
                        }];
                        
                    } forControlEvents:UIControlEventTouchUpInside];
                    
                    [cell.notInBtn bk_addEventHandler:^(id sender) {
                        NSLog(@"notInBtn");
                        [[OrdersService sharedInstance]executeDutyForID:allTaskID withStatus:@"3" withSuccessHandler:^(id result) {
                            [[DataEngine sharedInstance]showMessage:@"提交病人不在状态成功" withTitle:@"执行任务"];
                            [this setupData];
                        } andFailHandler:^(NSError *error, NSString *title) {
                            [[DataEngine sharedInstance]showMessage:[error description] withTitle:@"执行任务失败"];
                        }];
                        
                    } forControlEvents:UIControlEventTouchUpInside];
                    
                    [cell.refusedBtn bk_addEventHandler:^(id sender) {
                        NSLog(@"notInBtn");
                        [[OrdersService sharedInstance]executeDutyForID:allTaskID withStatus:@"2" withSuccessHandler:^(id result) {
                            [[DataEngine sharedInstance]showMessage:@"提交病人拒绝状态成功" withTitle:@"执行任务"];
                            [this setupData];
                        } andFailHandler:^(NSError *error, NSString *title) {
                            [[DataEngine sharedInstance]showMessage:[error description] withTitle:@"执行任务失败"];
                        }];
                        
                    } forControlEvents:UIControlEventTouchUpInside];
                    
                    
                }
                
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                return cell;
                
            }
            
            
            
        }else{
            static NSString *CellIdentifier = @"DutyViewListCell";
            
            DutyViewListCell *cell = (DutyViewListCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if(cell==nil){
                NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DutyViewListCell" owner:self options:nil];
                cell = [nib objectAtIndex:0];
            }
            
            
            if (indexPath.row <= [list count] ) {
                NSLog(@"index path row:%d",indexPath.row);
                NSDictionary* task = [list objectAtIndex:indexPath.row-1];
                cell.nameLab.text = [task valueForKey:@"任务内容"];
                NSLog(@"nr:%@",[task valueForKey:@"任务内容"]);
                cell.numberLab.text = [NSString stringWithFormat:@"%@ %@",[task valueForKey:@"剂量"],[task valueForKey:@"单位"]];
                
            }
            
            
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            return cell;
        }
        
    }else
    {
        
        static NSString *CellIdentifier = @"DutyViewCell";
        
        DutyViewCell *cell = (DutyViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell==nil){
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DutyViewCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
            cell.hookimg.image=[UIImage imageNamed:@"current-icon_s.png"];
            
        }
        
        //NSInteger taskIndex = indexPath.section;
        
        //NSDictionary* taskRecord = [_dataList objectAtIndex:taskIndex];
        
//        switch (indexPath.section) {
//            case 0:
//            case 4:
//            {
//                cell.img.image=[UIImage imageNamed:@"task-icon-01.png"];
//                cell.headimg.image=[UIImage imageNamed:@"patient-icon-s.png"];
//                cell.hookimg.hidden=NO;
//            }
//                break;
//            case 1:
//            case 2:
//            {
//                cell.img.image=[UIImage imageNamed:@"task-icon-02.png"];
//                cell.headimg.image=[UIImage imageNamed:@"patient-icon-s_grey.png"];
//                cell.hookimg.hidden=YES;
//            }
//                break;
//                
//            default:
//            {
//                cell.img.image=[UIImage imageNamed:@"task-icon-03.png"];
//                cell.headimg.image=[UIImage imageNamed:@"patient-icon-s_grey.png"];
//                cell.hookimg.hidden=YES;
//            }
//                break;
//        }
        
       // NSLog(@"任务:%@",taskRecord);
        cell.headimg.image=[UIImage imageNamed:@"patient-icon-s.png"];
        cell.hookimg.hidden=NO;
        cell.backgroundColor=[UIColor colorWithRed:140/255.0 green:201/255.0 blue:233/255.0 alpha:0.6];
        
        if ([taskType isEqualToString:@"给药"]) {
            cell.img.image=[UIImage imageNamed:@"task-icon-02.png"];
        }
        else{
             cell.img.image=[UIImage imageNamed:@"task-icon-03.png"];
        }
        NSNumber* status = [taskRecord valueForKey:@"status"];
        if ([status intValue] == 0) {
            cell.headimg.image=[UIImage imageNamed:@"patient-icon-s_grey.png"];
            cell.hookimg.hidden=YES;
            cell.backgroundColor=[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:0.6];
        }
        
        
        
        cell.contentLab.text=[taskRecord valueForKey:@"title"];
        cell.timeLab.text=[NSString stringWithFormat:@"%@",[taskRecord valueForKey:@"dateTime"]];
        cell.nameLab.text= [taskRecord valueForKey:@"xm"];
        
        
        //cell.titleLabel.text=@"111";
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        return cell;
    }
}


#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        if ([indexPath isEqual:self.selectIndex]) {
            self.isOpen = NO;
            [self didSelectCellRowFirstDo:NO nextDo:NO];
            self.selectIndex = nil;
            
        }else
        {
            if (!self.selectIndex) {
                self.selectIndex = indexPath;
                [self didSelectCellRowFirstDo:YES nextDo:NO];
                
            }else
            {
                
                [self didSelectCellRowFirstDo:NO nextDo:YES];
            }
        }
        
    }else
    {
        //        NSDictionary *dic = [_dataList objectAtIndex:indexPath.section];
        //        NSArray *list = [dic objectForKey:@"list"];
        //        NSString *item = [list objectAtIndex:indexPath.row-1];
        //        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:item message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles: nil] ;
        //        [alert show];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (void)didSelectCellRowFirstDo:(BOOL)firstDoInsert nextDo:(BOOL)nextDoInsert
{
    self.isOpen = firstDoInsert;
    
    //    UITableViewCell *cell = [self.expansionTableView cellForRowAtIndexPath:self.selectIndex];
    //    [cell changeArrowWithUp:firstDoInsert];
    
    [self.table_View beginUpdates];
    
    int section = self.selectIndex.section;
    
    NSDictionary* taskRecord = [self.tasks objectAtIndex:section];

    int contentCount = [[[_dataList objectAtIndex:section] objectForKey:@"list"] count];
	NSMutableArray* rowToInsert = [[NSMutableArray alloc] init];
	for (NSUInteger i = 1; i < contentCount + 2; i++) {
		NSIndexPath* indexPathToInsert = [NSIndexPath indexPathForRow:i inSection:section];
		[rowToInsert addObject:indexPathToInsert];
	}
	
	if (firstDoInsert)
    {   [self.table_View insertRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationTop];
    }
	else
    {
        [self.table_View deleteRowsAtIndexPaths:rowToInsert withRowAnimation:UITableViewRowAnimationTop];
    }
    
	rowToInsert=nil;
	
	[self.table_View endUpdates];
    if (nextDoInsert) {
        self.isOpen = YES;
        self.selectIndex = [self.table_View indexPathForSelectedRow];
        [self didSelectCellRowFirstDo:YES nextDo:NO];
    }
    if (self.isOpen) [self.table_View scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:YES];
}






-(void)leftBar_clicked:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
